package com.zykj.thread.concurrent.semphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author zhoulj(周利军) [1217102780@qq.com]
 * @Module ID:   <(模块)类编号，可以引用系统设计中的类编号>
 * @Comments: <对此类的描述，可以引用系统设计中的描述>
 * @JDK version used:      <JDK1.8> 10
 * @since 2019/1/15-17:10
 */
public class SemaphoreDemo {

    static int semaphoreCount = 3;
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();

        //TODO 信号量 可以控制 具体线程的个数
        final Semaphore semaphore = new Semaphore(semaphoreCount);

        for (int i = 0; i < 10; i++) {
            executorService.execute((Runnable)()->{
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "进入,  还有信号量：" + (semaphoreCount - semaphore.availablePermits()));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 回收信号量
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + "离开,  还有信号量：" + (semaphoreCount - semaphore.availablePermits()));
            });
        }


    }
}
